package com.xykj.deploy.login.service.impl;

import com.xykj.deploy.constants.LoginCache;
import com.xykj.deploy.login.entity.UserInfo;
import com.xykj.deploy.login.mapper.UserMapper;
import com.xykj.deploy.login.service.UserService;
import com.xykj.deploy.utils.JwtUtil;
import com.xykj.deploy.utils.RedisUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author hujingbo
 * @version 1.0
 * @description: 用户服务实现类
 * @date 2024-11-29 09:30
 */
@Slf4j
@Service
public class UserServiceImpl implements UserService {

    private final JwtUtil jwtUtil;
    private final RedisUtil redisUtil;
    private final UserDetailsService userDetailsService;

    @Resource
    private UserMapper userMapper;

    public UserServiceImpl(JwtUtil jwtUtil, RedisUtil redisUtil, UserDetailsService userDetailsService) {
        this.jwtUtil = jwtUtil;
        this.redisUtil = redisUtil;
        this.userDetailsService = userDetailsService;
    }

    /**
     * @description:
     * @param: username
     * password
     * @return: java.lang.String
     * @author hujingbo
     * @date: 2024-11-29 09:30
     */
    @Override
    public String login(UserInfo user, HttpServletResponse response) {
        // 验证用户身份
        String username = user.getUsername();
        String password = user.getPassword();
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);

        if (!password.equals(userDetails.getPassword())){
            return null;
        }

        if (userDetails != null) {
            // 生成 JWT token
            String token = jwtUtil.generateToken(username);

            // 如果记住我，延长 token 时间为7天
            boolean rememberMe = user.isRemember();
            long tokenExpirationTime = rememberMe ? 7 * 24 * 60 * 60 : 24 * 60 * 60;

            // 将 token 存入 Redis，有效期为7天（如果记住我）或1天（默认）
            redisUtil.set(LoginCache.LOGIN_PREFIX + username, token, tokenExpirationTime, TimeUnit.SECONDS);

            // 将 token 放入 Cookie，发送给前端
            Cookie cookie = new Cookie("auth_token", token);
            cookie.setHttpOnly(true);
            cookie.setMaxAge(rememberMe ? 7 * 24 * 60 * 60 : 3600);
            cookie.setPath("/");

            response.addCookie(cookie);
            return token;
        }

        return null;
    }

    /**
     * @description:
     * @param: token
     * @return: boolean
     * @author hujingbo
     * @date: 2024-11-29 09:31
     */
    @Override
    public boolean validateToken(String token) {
        if (jwtUtil.validateToken(token)) {
            String username = jwtUtil.getUsernameFromToken(token);
            String storedToken = (String) redisUtil.get(LoginCache.LOGIN_PREFIX + username);
            return token.equals(storedToken);
        }
        return false;
    }

    /**
     * @description:
     * @param: token
     * @return: void
     * @author hujingbo
     * @date: 2024-11-29 09:33
     */
    @Override
    public void logout(String token) {
        String username = jwtUtil.getUsernameFromToken(token);
        redisUtil.delete(LoginCache.LOGIN_PREFIX + username);
    }

    @Override
    public UserInfo getUserByToken(String token) {
        String username = jwtUtil.getUsernameFromToken(token);
        return userMapper.selectByUsername(username);
    }

    @Override
    public UserInfo updateUser(UserInfo userUpdateInfo) {
        return null;
    }
}
